<template>
  <div class="add-address-container">
    <van-address-edit
      :area-list="areaList"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="saveAddress"
      @change-detail="onChangeDetail"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { areaList as areaData } from '@vant/area-data'; // 使用命名导入

const router = useRouter();
const areaList = ref(areaData); // 使用命名导入的数据
const searchResult = ref([]);

const saveAddress = (content) => {
  if (content.name && content.tel && content.addressDetail) {
    // 从 localStorage 中获取已保存的地址列表
    let addresses = JSON.parse(localStorage.getItem('addresses') || '[]');
    
    // 添加新地址
    addresses.push({
      name: content.name,
      phone: content.tel,
      address: `${content.province} ${content.city} ${content.county} ${content.addressDetail}`
    });

    // 保存地址列表到 localStorage
    localStorage.setItem('addresses', JSON.stringify(addresses));

    // 显示保存成功的提示
    showToast('地址保存成功');

    // 返回上一页
    router.back();
  } else {
    // 显示填写完整的收货地址的提示
    showToast('请填写完整的收货地址');
  }
};

const onChangeDetail = (val) => {
  if (val) {
    searchResult.value = [
      {
        name: '黄龙万科中心',
        address: '杭州市西湖区',
      },
    ];
  } else {
    searchResult.value = [];
  }
};
</script>

<style scoped>
.add-address-container {
  height: 100%;
  background-color: #f5f5f5;
  padding: 20px;
}

</style>